package com.example.clock.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.clock.entity.Attend;
import com.example.clock.vo.AttendExcel;
import lombok.Data;
import lombok.Getter;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : lichengqian
 * 2024-08-23  15:03
 */
@Data
public class AttendExcelListener extends AnalysisEventListener<AttendExcel> {
    private List<Attend> list = new ArrayList<>();

    private String username;
    @Override
    public void invoke(AttendExcel attendExcel, AnalysisContext analysisContext) {
        Attend attend = new Attend();
        if(username.equals(attendExcel.getName())) {
            attend.setName(attendExcel.getName());
            attend.setCurrentDateTime(LocalDate.parse(attendExcel.getCurrentDateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            String clockUpTime = attendExcel.getClockUpTime();
            if (clockUpTime != null && !clockUpTime.isEmpty()) {
                if (clockUpTime.length() <= 10) {
                    clockUpTime = attend.getCurrentDateTime() + " " + clockUpTime;
                }
                attend.setClockUpTime(LocalDateTime.parse(clockUpTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            String clockDownTime = attendExcel.getClockDownTime();
            if (clockDownTime != null && !clockDownTime.isEmpty()) {
                if (clockDownTime.length() <= 10) {
                    clockDownTime = attend.getCurrentDateTime() + " " + clockDownTime;
                }
                attend.setClockDownTime(LocalDateTime.parse(clockDownTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            //计算加班时长
            if (attend.getClockUpTime() != null && attend.getClockDownTime() != null) {
                Duration between = Duration.between(attend.getClockUpTime(), attend.getClockDownTime());
                int length = (int) between.toMinutes() - 9 * 60;
                attend.setAdditionTimeLength(length);
                attend.setAdditionTimeStr(length / 60 + "小时" + length % 60 + "分");
            }
            list.add(attend);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
    public List<Attend> getAttendList() {
        return list;
    }
    public AttendExcelListener(String username) {
        this.username = username;
    }

}
